/**
 * Created by xc on 2016/05/12.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var ItbNotificationModel = function(obj){
    ItbBaseModel.call(this,obj);

    // 以下为表定义数据，需要的字段就填入
    //`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '消息id',
    //`type` int(3) NOT NULL DEFAULT '0' COMMENT '消息分类: 1:App普通msg(已废弃); 2:App横幅banner信息(已废弃)；3:App轮播图; 13:Web轮播图; 101:app活动通知(发送全员); 102:app系统通知(发送1~n个人)',
    //`number` int(3) NOT NULL DEFAULT '0' COMMENT '序号',
    //`title` text COMMENT '标题',
    //`message` text COMMENT '消息内容',
    //`image` text COMMENT '图片',
    //`url` text COMMENT '链接',
    //`start_time` datetime NOT NULL COMMENT '有效期开始日时',
    //`end_time` datetime DEFAULT NULL COMMENT '有效期结束日时',
    //`create_time` datetime NOT NULL,
    //`update_time` datetime NOT NULL,
    //`del_flg` int(1) NOT NULL DEFAULT '0',

};
ItbNotificationModel.prototype = new ItbBaseModel();

// 取得表名
ItbNotificationModel.prototype.getTableName = function(){
    return 'itb_notification';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbNotificationModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'id='+this.id;
}

//------------------------------------------------------------------
/* 获取通知消息
 * 参数 id
 * 参数 type
 * 参数 start_time: 预计开始日时, YYYYMMDDhhmmss (14位年月日十分秒)
 * 参数 end_time: 预计结束日时, YYYYMMDDhhmmss (14位年月日十分秒)
 * 参数 time: 预计日时, YYYYMMDDhhmmss (14位年月日十分秒)
 */
ItbNotificationModel.prototype.getMessage = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbNotificationModel.getMessage Err:'+err);
        }
        // Use the connection
        var sql = ' SELECT * FROM itb_notification t WHERE t.del_flg = 0 ';
        if (THIS.id) {
            sql += ' AND t.id= ' + THIS.id;
        }
        if (THIS.type) {
            sql += ' AND t.type= ' + THIS.type;
        }
        if (THIS.time || THIS.start_time || THIS.end_time) {
            if (THIS.start_time) {
                sql += ' AND t.start_time >= str_to_date("' + THIS.start_time + '","%Y%m%d%H%i%s") ';
            }
            if (THIS.end_time) {
                sql += ' AND t.end_time <= str_to_date("' + THIS.start_time + '","%Y%m%d%H%i%s") ';
            }
            if (THIS.time) {
                sql += ' AND t.start_time <= str_to_date("' + THIS.time + '","%Y%m%d%H%i%s") ';
                sql += ' AND t.end_time >= str_to_date("' + THIS.time + '","%Y%m%d%H%i%s") ';
            }
        } else {
            sql += ' AND t.start_time <= sysdate() ';
            sql += ' AND t.end_time >= sysdate() ';
        }

        if (THIS.order_by) {
            sql += ' ORDER BY ' + THIS.order_by;
        } else {
            sql += ' ORDER BY t.number ';
        }
        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            callback(error, result);
        });
    });
}

//------------------------------------------------------------------
/* 获取广播／活动消息
 * 参数: timestamp  查询[有效期]在此[时间戳]之后的活动广播 "YYYY-MM-DD hh:mm:ss" (15位 "年-月-日 时:分:秒" 字符串)
 *                 AND 当前系统时间在有效期内
 *
 */
ItbNotificationModel.prototype.getBroadcast = function(timestamp,  callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbNotificationModel.getBroadcast Err:'+err);
        }
        // Use the connection
        var DATE_FORMAT = '"%Y-%m-%d %H:%i:%S"';

        var sql =
            ' SELECT t.id, t.type, t.title, t.message, t.url, ' +
            ' DATE_FORMAT(t.start_time, '+DATE_FORMAT+') AS start_time, ' +
            ' DATE_FORMAT(t.create_time, '+DATE_FORMAT+') AS create_time ' +
            ' FROM itb_notification t WHERE t.del_flg = 0 ';
        sql += ' AND t.type=101 '; //101:app活动通知(发送全员);
        sql += ' AND t.start_time <= sysdate() and t.end_time >= sysdate() ';

        if(timestamp){
            //sql += ' AND t.create_time >= str_to_date("' + timestamp + '","%Y%m%d%H%i%s") ';
            sql += ' AND t.start_time > str_to_date("' + timestamp + '", '+DATE_FORMAT+') ';
        }

        sql += ' ORDER BY t.start_time ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            callback(error, result);
        });
    });
}

//------------------------------------------------------------------
/* 获取通知消息
 * 参数: userId 用户id
 * 参数: timestamp  查询[有效期]在此[时间戳]之后的通知 "YYYY-MM-DD hh:mm:ss" (15位 "年-月-日 时:分:秒" 字符串)
 *                 AND 当前系统时间在有效期内
 * 参数: state      通知消息状态(逗号连接): 10新建, 20已获取
 *
 */
ItbNotificationModel.prototype.getNotifications  = function(userId, timestamp, state, callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbNotificationModel.getNotifications Err:'+err);
        }
        // Use the connection
        var DATE_FORMAT = '"%Y-%m-%d %H:%i:%S"';

        var sql =
            ' SELECT t.id, t.type, t.title, t.message, t.url, n.id AS r_id, ' +
        // modified by xc 2017-05-24 start
            //' DATE_FORMAT(t.start_time, '+DATE_FORMAT+') AS start_time, ' +
            //' DATE_FORMAT(t.create_time, '+DATE_FORMAT+') AS create_time ' +
            ' DATE_FORMAT(n.create_time, '+DATE_FORMAT+') AS start_time, ' +
            ' DATE_FORMAT(n.create_time, '+DATE_FORMAT+') AS create_time ' +
        // modified by xc 2017-05-24 end
            ' FROM itb_notification t , itb_notify_user n ' +
            ' WHERE t.del_flg = 0 ' +
            ' AND t.type=102 ' +
            ' and t.id = n.`notify_id` ' +
            ' and t.del_flg=0 ' +
            ' and n.user_id= ' + userId ;

        sql += ' AND t.start_time <= sysdate() AND t.end_time >= sysdate() ';

        if(timestamp){
            //sql += ' AND n.create_time >= str_to_date("' + timestamp + '","%Y%m%d%H%i%s") ';
            sql += ' AND t.start_time > str_to_date("' + timestamp + '", '+DATE_FORMAT+') ';
        }

        if(state){
            sql += ' AND n.state IN ('+state+') ';
        }

        sql += ' ORDER BY t.start_time ';

        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            console.log();

            callback(error, result);
        });
    });
};

/**
 * 获取 APP 开屏广告信息
 *
 * @param screenW 需要的宽
 * @param screenH 需要的高
 * @param callback 回调
 * */
ItbNotificationModel.prototype.getAppAdInfo = function(screenW, screenH, callback) {


    pool.pool.getConnection(function(connectErr, connection) {
        if (connectErr) {
            console.log('ItbNotificationModel.getNotifications Err:'+err);
            return callback(connectErr, null);
        }
        var sql =
            " SELECT n.url AS url, " + // 跳转链接, 暂不处理
            "        n.image AS imgUrl, " +
            "        1 AS kind, " + // 类型 暂时只有1 标记纯图展示
            "        3 AS displayTime, " + // 展示时长, 数据库暂不记录, 默认为3: 单位: 秒
            "        n.chk_freq AS displayInterval " + // 两次开屏广告展示的最小间隔, 单位: 秒
            " FROM itb_notification n " +
            " WHERE n.type=5 " +
            "   AND SYSDATE() < n.end_time " +
            "   AND SYSDATE() > n.start_time " +
            "   AND n.del_flg = 0 " +
            " ORDER BY n.start_time DESC ";
        console.log(sql);
        connection.query(sql, function(queryErr, result) {
            // And done with the connection.
            connection.release();

            if(queryErr || result.length <= 0) {
                return callback(queryErr || '暂无开屏广告图信息', null);
            }
            return callback(queryErr, result[0]);
        });
    });
};


/**
 * 获取弹框信息_APP_6_6 添加
 * @param callback 回调
 * */
ItbNotificationModel.prototype.getActivityWindowInfo_app_v6_6 = function(callback) {

    pool.pool.getConnection(function(connectErr, connection) {
        if (connectErr) {
            console.log('ItbNotificationModel.getActivityWindowInfo_app_v6_6 Err:'+err);
            return callback(connectErr, null);
        }
        var sql = "  SELECT n.id,n.embed_url AS contentUrl,n.chk_freq as displayInterval,n.display_type as displayType," +
            "  n.w as windowW,n.h as windowH " +
            "  FROM itbour.itb_notification n " +
            "  WHERE n.type=7 " +
            "  AND SYSDATE() < n.end_time " +
            "  AND SYSDATE() > n.start_time " +
            "  AND n.del_flg=0";
        console.log(sql);
        connection.query(sql, function(queryErr, result) {
            // And done with the connection.
            connection.release();

            if(queryErr || !result || result.length <= 0) {
                return callback(queryErr || '暂无开屏弹框信息', null);
            }
            return callback(queryErr, result[0]);
        });
    });
};


// 导出
module.exports = ItbNotificationModel;